var canvas; //画布
var imagesbase = new Array(); //预加载图片
var imgbool = 0; //判断预加载完成
var border_len = 0;
var border_len1 = 0;
var border_len2 = 0;
var border_len_text = 0;
var border_len_text1 = 0;
var border_len_text2 = 0;
var x_select1 = 0,
	x_select2 = 0,
	y_select1 = 0,
	y_select2 = 0;
var minX = 0,
	minY = 0;
var maxWidth = 0,
	maxHeight = 0;
var select_most = 0;
var qiang_draw = 0;
var selectArray = new Array(); //用于储存多选时选择的元素
var selectPoin;
var istext = false,
	istext1 = false; //判断是否修改文字
var qiang_width = 4;
var kuanjia = 0;
var cengKey, cengKeyText, cengKeyQ; //被选中图片和文字各自的层数
var wangge = 0; //判断是否需要网格
var fontset = false; //判断是否插入文字
var x1 = 0,
	x2 = 0,
	y1 = 0,
	y2 = 0;
var y = '{"qiangarray":[]}&&{"imgarray":[]}&&{"textarray":[]}';
var historyBackView = new Array(),historyNextView = new Array(); //用于储存浏览历史视图；
historyBackView[0] = y;
var varSImg = false,
	open_magnet = true,
	kind = 0;
var imgObject = new createImage();
var wallObject = new createWall();
var wordObject = new createWord();
(function int() {
	//水印图片,网格图片
	var sources = {
		shuiyin: "style/images/shuiyin60.png",
		wangge: "style/images/ge.png"
	};
	loadImages(sources); //预加载
	keybord(); //键盘事件
	canvas = document.getElementById('canvas');
	context = canvas.getContext('2d');
	abc(); //绑定鼠标事件
	setTimeout(function() {
		//hasyuju();
		//默认至少有条border，以防无法进行多选
		if(wallObject.QBorder.length==0){
			wallObject.addWall(-1, -1, 0, 0, 0);//这条border显示不出来
		}
		drawImage2(wangge, 1);
	}, 500);
})();

/*//切换——是否自动贴墙
function ChangeMagnet() {
	//	open_magnet = !open_magnet;
	open_magnet = true;
}*/

//读取txt文件
function changeCanvase(txt) {
	txt = unescape(txt);//解密
	changeCanvasebytxt(txt,true);
}
//读取json字符串绘制视图
function changeCanvasebytxt(txt,b) {
	y = txt;
	hasyuju();
	drawImage2(wangge, 1,b);
}
//判断json字符串并存入对应元件对象数组
function hasyuju() {
	try {
		var obj1 = eval("(" + y.split('&&')[0] + ")");
		var obj2 = eval("(" + y.split('&&')[1] + ")");
		var obj3 = eval("(" + y.split('&&')[2] + ")");
		cleanCanvas(false);
		
		for(var wallobj of obj1.qiangarray) {
			wallObject.addWall(wallobj.QX1, wallobj.QY1, wallobj.QX2, wallobj.QY2, wallobj.QW, wallobj.QColor)
		};
		for(var imgobj of obj2.imgarray) {
			addimg(imgobj.imgSrc, 0, 0, 0, imgobj.iswall, imgobj.imgScaleX, imgobj.imgScaleY, imgobj.imgX, imgobj.imgY, imgobj.imgR);
		}
		for(var wordobj of obj3.textarray) {
			wordObject.addWord(wordobj.textX, wordobj.textY, wordobj.textSize, wordobj.textArray, wordobj.textColor);
		}
	} catch(e) {
		alert("保存码有误！");
	}
}
//绑定鼠标方法
function abc() {
	canvas.addEventListener('mousemove', function(e) {
		border_len1 = 0;
		border_len_text1 = 0;
		reDraw1(0, e);
	}, false);
	canvas.addEventListener('mousedown', function(e) {
		//判断是否画框架
		if(kuanjia) {
			x1 = 0, x2 = 0, y1 = 0, y2 = 0;
			var pos = windowToCanvas(canvas, e.clientX, e.clientY);
			x1 = pos.x;
			y1 = pos.y;
			//重定义画布鼠标移动事件
			canvas.onmousemove = function(event) {
				drawImage2(wangge, 1);
				context.beginPath();
				var pos1 = windowToCanvas(canvas, event.clientX, event.clientY);
				x2 = pos1.x;
				y2 = pos1.y;
				context.strokeStyle = "#000000";
				context.lineWidth = 2;
				context.setLineDash([10]);
				context.beginPath();
				context.strokeRect(x1, y1, x2 - x1, y2 - y1);
			}
		} 
		else if(istext) {
			addfont();
			istext = false;
		} 
		//判断是否完成编辑文字
		else if(!fontset && istext1) {
			changefont(cengKeyText);
		} 
		//判断是否画墙
		else if(qiang_draw) {
			var pos = windowToCanvas(canvas, e.clientX, e.clientY);
			wallObject.addWall(pos.x, pos.y, pos.x, pos.y, qiang_width);
			cengKeyQ = wallObject.QBorder.length - 1;
			imgObject.clearBorder(imgObject.imgUrl.length);
			wordObject.clearBorder(wordObject.textArray.length);
			wallObject.clearBorder(cengKeyQ);
			drawImage2(wangge, 1);
			//重定义画布鼠标移动事件
			canvas.onmousemove = function(e) {
				var pos1 = windowToCanvas(canvas, e.clientX, e.clientY);
				wallObject.QX2[wallObject.QX2.length - 1] = pos1.x;
				wallObject.QY2[wallObject.QY2.length - 1] = pos1.y;
				drawImage2(wangge, 1);
			}
		} else {
			border_len = 0;
			border_len_text = 0;
			border_len_text2 = 0;
			for(var j = 0; j < wallObject.QBorder.length + imgObject.imgUrl.length + wordObject.textArray.length; j++) {
				reDraw(j, e);
			}
		}
	}, false);
	canvas.addEventListener('mouseup', function(e) {
		canvas.onmousemove = null;
		canvas.onmouseup = null;
		//判断是否画框架
		if(kuanjia) {
			if(x2 != 0 && y2 != 0) {
				context.setLineDash([0]);
				if(x1 < x2) {
					wallObject.addWall(x1 - qiang_width / 2, y2, x2 + qiang_width / 2, y2, qiang_width);
					wallObject.addWall(x1 - qiang_width / 2, y1, x2 + qiang_width / 2, y1, qiang_width);
				} else {
					wallObject.addWall(x1 + qiang_width / 2, y2, x2 - qiang_width / 2, y2, qiang_width);
					wallObject.addWall(x1 + qiang_width / 2, y1, x2 - qiang_width / 2, y1, qiang_width);
				}
				wallObject.addWall(x1, y1, x1, y2, qiang_width);
				wallObject.addWall(x2, y1, x2, y2, qiang_width);
				cengKeyQ = wallObject.QBorder.length;
				cengKey = imgObject.imgUrl.length;
				cengKeyText = wordObject.textArray.length;
				imgObject.clearBorder(cengKey);
				wordObject.clearBorder(cengKeyText);
				wallObject.clearBorder(cengKeyQ);
				drawImage2(wangge, 1,true);
			}
		}
		//判断是否进行了多选
		else if((x_select2 - x_select1) > 0 && (y_select2 - y_select1) > 0) {
			selectImg(x_select1, x_select2, y_select1, y_select2);
			x_select1 = 0;
			x_select2 = 0;
			y_select1 = 0;
			y_select2 = 0;
		}
		//判断是否画墙
		else if(qiang_draw) {
			cengKey = imgObject.imgUrl.length;
			cengKeyText = wordObject.textArray.length;
			cengKeyQ = wallObject.QBorder.length;
		} else if(selectArray.length == 0) {//没有多选中元件
			drawImage2(wangge, 1,true);
		}
		canvas.style.cursor = "auto";
		//判断自动贴墙
		//console.info(varSImg);
		if(varSImg && open_magnet) {
			var SImg = varSImg - 1;
			var wall = imgObject.magnet[SImg] - 1;
			var calculationX = imgObject.imgX[SImg] + imgObject.imgScaleX[SImg] * imgObject.imgUrl[SImg].width;
			var calculationY = imgObject.imgY[SImg] + imgObject.imgScaleY[SImg] * imgObject.imgUrl[SImg].height;
			var angle = getAngle(wallObject.QX1[wall], wallObject.QY1[wall], wallObject.QX2[wall], wallObject.QY2[wall]);
			//console.info(angle % 180);
			angle = angle % 180
			var angle2 = imgObject.imgR[SImg];
			if(angle < 93 && angle > 87) {
				if(imgObject.imgX[SImg] < (wallObject.QX1[wall] + wallObject.QW[wall] + imgObject.imgScaleX[SImg] * imgObject.imgUrl[SImg].width / 2) &&
					imgObject.imgX[SImg] > (wallObject.QX1[wall] - wallObject.QW[wall] - imgObject.imgScaleX[SImg] * imgObject.imgUrl[SImg].width / 2)) {
					imgObject.imgX[SImg] = wallObject.QX1[wall] - wallObject.QW[wall] / 2;
					if((angle2 % 90) != 0) {
						if((angle2 % 90) < 45) {
							imgObject.imgR[SImg] = 0+90*parseInt(angle2/90);
						} else {
							if(parseInt(angle2/90)!=3){
								imgObject.imgR[SImg] = 90+90*parseInt(angle2/90);
							}else{
								imgObject.imgR[SImg] = 0;
							}
						}
					}
					if(imgObject.imgR[SImg] == 90 || imgObject.imgR[SImg] == 270) {
						var piancha = (imgObject.imgScaleY[SImg] * imgObject.imgUrl[SImg].height - imgObject.imgScaleX[SImg] * imgObject.imgUrl[SImg].width) / 2;
						imgObject.imgX[SImg] += piancha;
					}
				} else if(calculationX < (wallObject.QX1[wall] + wallObject.QW[wall] + imgObject.imgScaleX[SImg] * imgObject.imgUrl[SImg].width / 2) &&
					calculationX > (wallObject.QX1[wall] - wallObject.QW[wall] - imgObject.imgScaleX[SImg] * imgObject.imgUrl[SImg].width / 2)) {
					imgObject.imgX[SImg] = wallObject.QX1[wall] - imgObject.imgScaleX[SImg] * imgObject.imgUrl[SImg].width + wallObject.QW[wall] / 2;

					if((angle2 % 90) != 0) {
						if((angle2 % 90) < 45) {
							imgObject.imgR[SImg] = 0+90*parseInt(angle2/90);
						} else {
							if(parseInt(angle2/90)!=3){
								imgObject.imgR[SImg] = 90+90*parseInt(angle2/90);
							}else{
								imgObject.imgR[SImg] = 0;
							}
						}
					}
					if(imgObject.imgR[SImg] == 90 || imgObject.imgR[SImg] == 270) {
						var piancha = (imgObject.imgScaleY[SImg] * imgObject.imgUrl[SImg].height - imgObject.imgScaleX[SImg] * imgObject.imgUrl[SImg].width) / 2;

						imgObject.imgX[SImg] -= piancha;
					}
				}
			} else if(angle < 3 && angle > -3) {
				if(imgObject.imgY[SImg] < (wallObject.QY1[wall] + wallObject.QW[wall] + imgObject.imgScaleY[SImg] * imgObject.imgUrl[SImg].height / 2) &&
					imgObject.imgY[SImg] > (wallObject.QY1[wall] - wallObject.QW[wall] - imgObject.imgScaleY[SImg] * imgObject.imgUrl[SImg].height / 2)) {
					imgObject.imgY[SImg] = wallObject.QY1[wall] - wallObject.QW[wall] / 2;

					if((angle2 % 90) != 0) {
						if((angle2 % 90) < 45) {
							imgObject.imgR[SImg] = 0+90*parseInt(angle2/90);
						} else {
							if(parseInt(angle2/90)!=3){
								imgObject.imgR[SImg] = 90+90*parseInt(angle2/90);
							}else{
								imgObject.imgR[SImg] = 0;
							}
						}
					}
					if(imgObject.imgR[SImg] == 90 || imgObject.imgR[SImg] == 270) {
						var piancha = (imgObject.imgScaleY[SImg] * imgObject.imgUrl[SImg].height - imgObject.imgScaleX[SImg] * imgObject.imgUrl[SImg].width) / 2;

						imgObject.imgY[SImg] -= piancha;
					}
				} else if(calculationY < (wallObject.QY1[wall] + wallObject.QW[wall] + imgObject.imgScaleY[SImg] * imgObject.imgUrl[SImg].height / 2) &&
					calculationY > (wallObject.QY1[wall] - wallObject.QW[wall] - imgObject.imgScaleY[SImg] * imgObject.imgUrl[SImg].height / 2)) {
					imgObject.imgY[SImg] = wallObject.QY1[wall] - imgObject.imgScaleY[SImg] * imgObject.imgUrl[SImg].height + wallObject.QW[wall] / 2;

					if((angle2 % 90) != 0) {
						if((angle2 % 90) < 45) {
							imgObject.imgR[SImg] = 0+90*parseInt(angle2/90);
						} else {
							if(parseInt(angle2/90)!=3){
								imgObject.imgR[SImg] = 90+90*parseInt(angle2/90);
							}else{
								imgObject.imgR[SImg] = 0;
							}
						}
					}
					if(imgObject.imgR[SImg] == 90 || imgObject.imgR[SImg] == 270) {
						var piancha = (imgObject.imgScaleY[SImg] * imgObject.imgUrl[SImg].height - imgObject.imgScaleX[SImg] * imgObject.imgUrl[SImg].width) / 2;
						imgObject.imgY[SImg] += piancha;
					}
				}
			} else {

			}
			drawImage2(wangge, 1,true);
		}
		saveHistory();
	}, false);
}

//保存历史
function saveHistory(){
	var toJson = strJsonToJson();
	if(toJson != historyBackView[historyBackView.length - 1]) {
		if(historyBackView.length>=20){
			historyBackView.splice(0,1)
		}
		historyBackView.push(toJson); //视图存进历史
	}
}

function getAngle(px1, py1, px2, py2) {
	//两点的x、y值
	x = px2 - px1;
	y = py2 - py1;
	hypotenuse = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
	//斜边长度
	cos = x / hypotenuse;
	radian = Math.acos(cos);
	//求出弧度
	angle = 180 / (Math.PI / radian);
	//用弧度算出角度        
	if(y < 0) {
		angle = -angle;
	} else if((y == 0) && (x < 0)) {
		angle = 180;
	}
	return angle;
}

//画框架（四面墙）
function kuangjia(B) {
	qiang_draw = 0;
	/*if (kuanjia) {
		kuanjia = 0;
	} else {*/
	kuanjia = B;
	/*}*/
	wallObject.clearBorder(wallObject.QBorder.length);
	cengKey = wallObject.QBorder.length;
	drawImage2(wangge, 1);
}
//多选（限图片与墙壁）
function selectImg(x1, x2, y1, y2) {
	minX = x2;
	minY = y2;
	maxWidth = 0;
	maxHeight = 0;
	for(var i = 0; i < imgObject.imgUrl.length; i++) {
		var outer = imgObject.getOuter(i);
		if(outer.x1 > x1 && outer.x2 < x2) {
			if(outer.y1 > y1 && outer.y2 < y2) {
				imgObject.imgBorder[i] = 1;
				selectArray.push(i);
				if(outer.x2 > maxWidth) {
					maxWidth = outer.x2 + 16;
				}
				if(outer.y2 > maxHeight) {
					maxHeight = outer.y2 + 16;
				}
				if(outer.x1 < minX) {
					minX = outer.x1 - 16;
				}
				if(outer.y1 < minY) {
					minY = outer.y1 - 16;
				}
			}
		}
	}
	selectPoin = selectArray.length;
	for(var i = 0; i < wallObject.QBorder.length; i++) {
		var qx1 = wallObject.QX1[i];
		var qy1 = wallObject.QY1[i];
		var qx2 = wallObject.QX2[i];
		var qy2 = wallObject.QY2[i];
		if(qx2 < qx1) {
			var select = qx1;
			qx1 = qx2;
			qx2 = select;
		}
		if(qy2 < qy1) {
			var select = qy1;
			qy1 = qy2;
			qy2 = select;
		}
		if(qx1 > x1 && qx2 < x2) {
			if(qy1 > y1 && qy2 < y2) {
				wallObject.QBorder[i] = 1;
				selectArray.push(i);
				if(qx1 < minX) {
					minX = qx1 - 8;
				}
				if(qy1 < minY) {
					minY = qy1 - 8;
				}
				if(qx2 > maxWidth) {
					maxWidth = qx2 + 8
				}
				if(qy2 > maxHeight) {
					maxHeight = qy2 + 8
				}
			}
		}
	}
	drawImage2(wangge, 1,true);
	maxWidth -= minX;
	maxHeight -= minY;
	if(selectArray.length > 0) {
		context.strokeStyle = "#000000";
		context.strokeRect(minX, minY, maxWidth, maxHeight);
		select_most = 1;
	}
}
//切换画墙模式
function qiang(B) {
	kuanjia = 0;
	/*if (qiang_draw) {
		qiang_draw = 0;
	} else {*/
	qiang_draw = B;
	/*}*/
	wallObject.clearBorder(wallObject.QBorder.length);
	cengKey = wallObject.QBorder.length;
	drawImage2(wangge, 1,true);
}
//改变墙的宽度
function Q_W(w) {
	qiang_width = w;
}
//对齐
function left(f) {
	if(select_most && selectArray.length > 0) {
		for(var i = 0; i < selectPoin; i++) {
			var j = selectArray[i];
			if(f == 1) {
				imgObject.imgX[j] = minX + 8;
			} else if(f == 2) {
				imgObject.imgX[j] = minX + maxWidth - imgObject.imgUrl[j].width * imgObject.imgScaleX[j] - 8;
			} else if(f == 3) {
				imgObject.imgY[j] = minY + 8;
			} else if(f == 4) {
				imgObject.imgY[j] = minY + maxHeight - imgObject.imgUrl[j].height * imgObject.imgScaleY[j] - 8;
			} else if(f == 5) {
				imgObject.imgX[j] = minX + maxWidth / 2 - imgObject.imgUrl[j].width * imgObject.imgScaleX[j] / 2 - 8;
			} else if(f == 6) {
				imgObject.imgY[j] = minY + maxHeight / 2 - imgObject.imgUrl[j].height * imgObject.imgScaleY[j] / 2 - 8;
			}
		}
		drawImage2(wangge, 1,true);
		context.strokeRect(minX, minY, maxWidth, maxHeight);
	}
}
//切换至文字模式
function Fontset() {
	fontset = true;
	istext1 = false;
	$("#text1").hide();
	imgObject.clearBorder(imgObject.imgUrl.length);
	wordObject.clearBorder(wordObject.textArray.length);
	drawImage2(wangge, 1);
	cengKey = imgObject.imgUrl.length;
	cengKeyText = wordObject.textArray.length;
	var top = canvas.offsetTop + canvas.height / 2;
	var left = canvas.offsetLeft + canvas.width / 2;
	$("#text").css("top", top);
	$("#text").css("left", left);
	var color = $("#color").get(0).value;
	$("#text").css("color", color);
	$("#text").show().focus();
	canvas.style.cursor = "text";
	istext = true;
	fontset = false;
	if(!istext1) {
		istext = true;
	}
}
//键盘事件
function keybord(j) {
	document.onkeydown = function(event) {
		var e = event || window.event || arguments.callee.caller.arguments[0];
		if(e && e.keyCode == 13) { //按Enter
			if(!istext1) {
				addfont();
				istext = false;
			} else if(!fontset && istext1) {
				changefont(j);
			}
		} else if(e && e.keyCode == 8) { //按Backspace
			remove1();
		} else if(e && e.keyCode == 38) { //按上微调
			deviation(0, -1);
		} else if(e && e.keyCode == 40) { //按下微调
			deviation(0, 1);
		} else if(e && e.keyCode == 37) { //按左微调
			deviation(-1, 0);
		} else if(e && e.keyCode == 39) { //按右微调
			deviation(1, 0);
		} else if(e.ctrlKey && e.shiftKey && e.which == 90) {//ctrl+shift+z前进
			nextone();
		} else if(e.ctrlKey && e.which == 90) {//ctrl+z后退
			backone();
		}
	}
}
//后退功能
function backone(){
	if(historyBackView.length > 1) {
		historyNextView.push(historyBackView[historyBackView.length - 1]);
		historyBackView.splice((historyBackView.length - 1),1);
		changeCanvasebytxt(historyBackView[historyBackView.length - 1],false);
	}else{
		alert("不能再后退了。");
	}
}
//前进功能
function nextone(){
	if(historyNextView.length > 0) {
		historyBackView.push(historyNextView[historyNextView.length - 1]);
		changeCanvasebytxt(historyNextView[historyNextView.length - 1],false);
		historyNextView.pop();
	}else{
		alert("不能再前进了。");
	}
}
//增加文字
function addfont() {
	var text = $("#text").get(0).value;
	$("#text").hide();
	imgObject.clearBorder(imgObject.imgUrl.length);
	wallObject.clearBorder(wallObject.QBorder.length);
	if(text != "") {
		$("#text").get(0).value = "";
		var tt = $("#text").css("top");
		tt = tt.substring(0, tt.lastIndexOf('px'));
		var tl = $("#text").css("left");
		tl = tl.substring(0, tl.lastIndexOf('px'));
		var ct = canvas.offsetTop;
		var cl = canvas.offsetLeft;
		var color = $("#color").get(0).value;
		wordObject.addWord(tl - cl,tt - ct,16,text,color);
		cengKeyText = wordObject.textArray.length - 1;
		wordObject.clearBorder(cengKeyText);
		cengKey = imgObject.imgUrl.length;
		drawImage2(wangge, 1,true);
	}
	istext1 = false;
	canvas.style.cursor = "auto";
	select_most = 0;
	selectArray = new Array();
}
//修改文字
function changefont(j) {
	wordObject.textArray[j] = $("#text1").get(0).value;
	wordObject.textColor[j] = $("#color").get(0).value;
	istext1 = false;
	$("#text1").hide();
	wordObject.clearBorder(j);
	drawImage2(wangge, 1,true);
	$("#text1").get(0).value = "";
	cengKeyText = j;
	cengKey = imgObject.imgUrl.length;
	cengKeyQ = wallObject.QBorder.length;
}

function up() {
	if(cengKey < imgObject.imgUrl.length) {
		upimgforone(cengKey, 0);
		imgObject.clearBorder(cengKey);
	} else if(cengKeyText < wordObject.textArray.length) {
		upimgforone(cengKeyText, 1);
		imgObject.clearBorder(cengKeyText);
	}
	drawImage2(wangge, 1,true);
}

function upMax() {
	if(cengKey < imgObject.imgUrl.length) {
		upimg(cengKey, 0);
		imgObject.clearBorder(cengKey);
	} else if(cengKeyText < wordObject.textArray.length) {
		upimg(cengKeyText, 1);
		wordObject.clearBorder(cengKeyText);
	}
	drawImage2(wangge, 1,true);
}

function down() {
	if(cengKey < imgObject.imgUrl.length) {
		downimgforone(cengKey, 0);
		imgObject.clearBorder(cengKey);
	} else if(cengKeyText < wordObject.textArray.length) {
		downimgforone(cengKeyText, 1);
		wordObject.clearBorder(cengKeyText);
	}
	drawImage2(wangge, 1,true);
}

function downMax() {
	if(cengKey < imgObject.imgUrl.length) {
		downimg(cengKey, 0);
		imgObject.clearBorder(0);
	} else if(cengKeyText < wordObject.textArray.length) {
		downimg(cengKeyText, 1);
		wordObject.clearBorder(0);
	}
	drawImage2(wangge, 1,true);
}
//旋转图片
var clockwise = function(r) {
	imgObject.clockwise(r);
	saveHistory();
};
//图片预加载
function loadImages(sources) {
	var count = 0,
		images = {},
		imgNum = 0;
	for(src in sources) {
		imgNum++;
	}
	for(src in sources) {
		images[src] = new Image();
		images[src].crossOrigin = "*";
		images[src].onload = function() {
			if(++count >= imgNum) {
				imgbool = count;
			}
		}
		images[src].src = sources[src];
		imagesbase.push(images[src]);
	}
}
//新增图片
function addimg(imgsrc, width, height, event, iswall, S_caleX, S_caleY, oX, oY, oR) {
	wordObject.clearBorder(wordObject.textArray.length);
	wallObject.clearBorder(wallObject.QBorder.length);
	if(imgbool == imagesbase.length) {
		imgObject.addImg(imgsrc, width, height, event, iswall, S_caleX, S_caleY, oX, oY, oR);
		select_most = 0;
		selectArray = new Array();
	}
}

//微调选中
function deviation(x, y) {
	if(select_most && selectArray.length > 0) {
		for(var i = selectPoin - 1; i >= 0; i--) {
			imgObject.imgX[i] += x;
			imgObject.imgY[i] += y;
		}
		for(var i = selectArray.length; i > selectPoin; i--) {
			var j = selectArray[i - 1];
			wallObject.QX1[j] += x;
			wallObject.QX2[j] += x;
			wallObject.QY1[j] += y;
			wallObject.QY2[j] += y;
		}
		minX += x;
		minY += y;
		drawImage2(wangge, 1,true);
		context.strokeRect(minX, minY, maxWidth, maxHeight);
	} else {
		if(cengKeyText < wordObject.textArray.length) {
			wordObject.textX[cengKeyText] += x;
			wordObject.textY[cengKeyText] += y;
			drawImage2(wangge, 1,true);
			return;
		} else if(cengKey < imgObject.imgUrl.length) {
			imgObject.imgX[cengKey] += x;
			imgObject.imgY[cengKey] += y;
			drawImage2(wangge, 1,true);
			return
		} else if(cengKeyQ < wallObject.QBorder.length) {
			wallObject.QX1[cengKeyQ] += x;
			wallObject.QX2[cengKeyQ] += x;
			wallObject.QY1[cengKeyQ] += y;
			wallObject.QY2[cengKeyQ] += y;
			drawImage2(wangge, 1,true);
			return;
		}
	}
}
//删除选中
function remove1() {
	//防止编辑文字时触发
	if(fontset || !istext1){
		if(select_most && selectArray.length > 0) {
			for(var i = selectPoin - 1; i >= 0; i--) {
				imgObject.removeImg(selectArray[i]);
			}
			for(var i = selectArray.length - 1; i >= selectPoin; i--) {
				wallObject.removeWall(selectArray[i]);
			}
			selectArray = new Array();
			drawImage2(wangge, 1,true);
			saveHistory()
			cengKeyText = wordObject.textArray.length;
		} else {
			if(cengKeyText < wordObject.textArray.length) {
				wordObject.removeWord(cengKeyText);
				drawImage2(wangge, 1,true);
				saveHistory()
				return;
			} else if(cengKey < imgObject.imgUrl.length) {
				imgObject.removeImg(cengKey);
				drawImage2(wangge, 1,true);
				saveHistory()
				return
			} else if(cengKeyQ < wallObject.QBorder.length) {
				wallObject.removeWall(cengKeyQ);
				drawImage2(wangge, 1,true);
				saveHistory()
				return;
			}
		}
	}
}
//改变文字颜色
function changecolor(color) {
	for(i of Object.keys(wordObject.textBorder)) {
		if(wordObject.textBorder[i] == 1) {
			wordObject.textColor[i] = color;
		}
	}
	drawImage2(wangge, 1,true);
}
//改变墙壁颜色
function changecolorQ(color) {
	wallObject.QColor[cengKeyQ] = color;
	drawImage2(wangge, 1,true);
}
//清屏;b,是否清空历史
function cleanCanvas(b) {
	varSImg = false;
	imgObject.clean();
	wallObject.clean();
	
	wordObject.clean();
	//默认至少有条border，以防无法进行多选
	/*if(wallObject.QBorder.length==0){
		wallObject.addWall(-1, -1, 0, 0, 0);//这条border显示不出来
	}*/
	drawImage2(wangge, 1,false);
	if(b){
		historyBackView = new Array(),historyNextView = new Array(); //清空历史；
		historyBackView[0] = y;
	}
}
//图片置顶
function upimg(i, font) {
	if(!font) {
		imgObject.up(i);
	} else {
		wordObject.up(i);
	}
}
//图片置顶一层
function upimgforone(i, font) {
	if(!font) {
		imgObject.upforone(i);
	} else {
		wordObject.upforone(i);
	}
}
//图片置底
function downimg(i, font) {
	if(!font) {
		imgObject.down(i);
	} else {
		wordObject.down(i);
	}
}
//图片置底一层
function downimgforone(i, font) {
	if(!font) {
		imgObject.downforone(i);
	} else {
		wordObject.downforone(i);
	}
}

//添加水印图片（水平间隔原图片宽度1/4，垂直间隔原图片高度1/8，顺时针30度）
function addshuiyin() {
	context.beginPath();
	var m = canvas.width / (imagesbase[0].width * 0.5);
	var n = canvas.height / (imagesbase[0].width * 0.5);
	for(var i = 0; i < m + 1; i++) {
		for(var j = -1; j < (n + 1) * 2; j++) {
			context.beginPath();
			context.translate(imagesbase[0].width * 0.5 * i + imagesbase[0].width * 0.25, imagesbase[0].height * 0.5 * j + imagesbase[0].height * 0.25);
			context.rotate(Math.PI / 180 * 30);
			context.translate(-imagesbase[0].width * 0.5 * i - imagesbase[0].width * 0.25, -imagesbase[0].height * 0.5 * j - imagesbase[0].height * 0.25);
			context.drawImage(imagesbase[0], imagesbase[0].width * 0.9 * i, imagesbase[0].height * 1.3 * j, imagesbase[0].width * 0.5, imagesbase[0].height * 0.5);
			context.translate(imagesbase[0].width * 0.5 * i + imagesbase[0].width * 0.25, imagesbase[0].height * 0.5 * j + imagesbase[0].height * 0.25);
			context.rotate(Math.PI / 180 * -30);
			context.translate(-imagesbase[0].width * 0.5 * i - imagesbase[0].width * 0.25, -imagesbase[0].height * 0.5 * j - imagesbase[0].height * 0.25);
			context.stroke();
		}
	}
}
//网格
function addge() {
	context.beginPath();
	context.drawImage(imagesbase[1], 0, 0);
}
//绘制画布。ge：是否显示网格；shuiyin：是否添加水印；isSaveHistory：是否添加到历史记录；
function drawImage2(ge, shuiyin,isSaveHistory) {
	wangge = ge;
	context.clearRect(0, 0, canvas.width, canvas.height);
	context.beginPath();
	context.fillStyle = "#fff";
	context.fillRect(0, 0, canvas.width, canvas.height);
	//绘制网格图片
	if(ge) { 
		addge();
	}
	//循环绘制元件
	for(var i of Object.keys(wallObject.QW)) {
		wallObject.drawWall(context, i);
	}
	for(var i of Object.keys(imgObject.imgUrl)) {
		imgObject.drawImg(context, i);
	}
	for(var i of Object.keys(wordObject.textArray)) {
		wordObject.drawWord(context, i);
	}
	//排布水印图片
	if(shuiyin) {
		//context.drawImage(imagesbase[0], canvas.width - imagesbase[0].width * 0.5 - 10, canvas.height - imagesbase[0].height * 0.5 - 10, imagesbase[0].width * 0.5, imagesbase[0].height * 0.5);
	}
	//添加到历史记录
	if(isSaveHistory){
		saveHistory();
	}
	
}

//绑定元件事件
function reDraw(j, event) {
	//var context = canvas.getContext("2d");
	//获取相对画布的坐标
	var pos = windowToCanvas(canvas, event.clientX, event.clientY);
	//判断是否多选及有包含中元件
	if(select_most && selectArray.length > 0) {
		//var context = canvas.getContext("2d");
		context.strokeStyle = "#000000";
		context.rect(minX, minY, maxWidth, maxHeight);
		//移动全部多选时选中的元件（仅图片与墙壁）
		if(pos && context.isPointInPath(pos.x, pos.y)) {
			//重定义画布鼠标移动事件
			canvas.onmousemove = function(event) {
				canvas.style.cursor = "move";
				var pos1 = windowToCanvas(canvas, event.clientX, event.clientY);
				var x = pos1.x - pos.x;
				var y = pos1.y - pos.y;
				pos = pos1;
				for(var i of Object.keys(selectArray)) {
					var q = selectArray[i];
					if(i >= selectPoin) {
						wallObject.QX1[q] += x;
						wallObject.QY1[q] += y;
						wallObject.QX2[q] += x;
						wallObject.QY2[q] += y;
					} else {
						imgObject.imgX[q] += x;
						imgObject.imgY[q] += y;
					}
				}
				minX += x;
				minY += y;
				drawImage2(wangge, 1);
				context.strokeRect(minX, minY, maxWidth, maxHeight);
			}
		} else {
			selectArray = new Array();
			select_most = 0;
			minX = 0;
			minY = 0;
			maxWidth = 0;
			maxHeight = 0;
			imgObject.clearBorder(imgObject.imgUrl.length);
		}
	} else {
		//绑定所有元件的鼠标事件
		if(j < wallObject.QBorder.length) {
			wallObject.binding(j, context, canvas, pos);
		} else if(j < imgObject.imgUrl.length + wallObject.QBorder.length) {
			imgObject.binding(j - wallObject.QBorder.length, context, canvas, pos);
		} else {
			wordObject.binding(j - imgObject.imgUrl.length - wallObject.QBorder.length, context, canvas, pos);
		}
	
	}
}
//绑定鼠标停留在元件改变状态的事件
function reDraw1(j, event) {
	//var context = canvas.getContext("2d");
	var pos = windowToCanvas(canvas, event.clientX, event.clientY);
	if(qiang_draw) {
		canvas.style.cursor = "auto";
	} else if(select_most && selectArray.length > 0) {
		//context = canvas.getContext("2d");
		context.strokeStyle = "#000000";
		context.rect(minX, minY, maxWidth, maxHeight);
		if(pos && context.isPointInPath(pos.x, pos.y)) {
			canvas.style.cursor = "move";
		} else {
			canvas.style.cursor = "auto";
		}
	} else {
		//绑定所有元件的鼠标停留事件
		if(cengKeyText < wordObject.textArray.length) {
			wordObject.binding2(cengKeyText, context, canvas, pos);
		} else if(cengKey < imgObject.imgUrl.length) {
			imgObject.binding2(cengKey, context, canvas, pos);
		} else if(cengKeyQ < wallObject.QBorder.length) {
			wallObject.binding2(cengKeyQ, context, canvas, pos)
		}
	}
}

//生成图片
function copyimage(event, IsReturn) {
	imgObject.clearBorder(imgObject.imgUrl.length);
	wordObject.clearBorder(wordObject.textArray.length);
	wallObject.clearBorder(wallObject.QBorder.length);
	var ge = wangge;
	drawImage2(0, 0);
	//addshuiyin();
	var img_png_src = canvas.toDataURL("image/png");
	document.getElementById("image_png").src = img_png_src;
	$("#imgUrl").attr("download", $("#image_png").attr("src"));
	//SaveAs5();
	if(!!window.ActiveXObject || "ActiveXObject" in window) {
		$("#blackbg").show();
		$("#image_png-div").show();
	} else {
		var date = new Date();
		saveFile(img_png_src, date.getHours() + '' + date.getMinutes() + '' + date.getSeconds() + "户型图.png");
	}
	drawImage2(ge, 1);
}
//获取坐标
function windowToCanvas(canvas, x, y) {
	var bbox = canvas.getBoundingClientRect();
	return {
		x: x - bbox.left - (bbox.width - canvas.width) / 2,
		y: y - bbox.top - (bbox.height - canvas.height) / 2
	};
}
/**
 * 在本地进行文件保存
 * @param  {String} data     要保存到本地的图片数据
 * @param  {String} filename 文件名
 */
var saveFile = function(data, filename) {
	var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
	save_link.href = data;
	save_link.download = filename;

	var event = document.createEvent('MouseEvents');
	event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
	save_link.dispatchEvent(event);
};
//将视图转为json字符串
function strJsonToJson() {
	var tq = '{"qiangarray":[';
	for(var i of Object.keys(wallObject.QBorder)) {
		tq += '{"QBorder":' + 0 + ',"QX1":' + wallObject.QX1[i] + ',"QX2":' + wallObject.QX2[i] + ',"QY1":' + wallObject.QY1[i] + ',"QY2":' + wallObject.QY2[i] + ',"QW":' + wallObject.QW[i] + ',"QColor":"' + wallObject.QColor[i] + '"},';
	}
	tq += "]}";
	var timg = '{"imgarray":[';
	for(var i of Object.keys(imgObject.imgUrl)) {
		var src = "style" + imgObject.imgUrl[i].src.split("/style")[1];
		timg += '{"iswall":' + imgObject.iswall[i] + ',"imgX":' + imgObject.imgX[i] + ',"imgY":' + imgObject.imgY[i] + ',"imgR":' + imgObject.imgR[i] + ',"imgBorder":' + 0 + ',"imgScaleX":' + imgObject.imgScaleX[i] + ',"imgScaleY":' + imgObject.imgScaleY[i] + ',"imgSrc":' + '"' + src + '"' + '},';
	}
	timg += "]}";
	var ttext = '{"textarray":[';
	for(var i of Object.keys(wordObject.textArray)) {
		ttext += '{"textX":' + wordObject.textX[i] + ',"textY":' + wordObject.textY[i] + ',"textBorder":' + 0 + ',"textSize":' + wordObject.textSize[i] + ',"textColor":' + '"' + wordObject.textColor[i] + '"' + ',"textArray":' + '"' + wordObject.textArray[i] + '"' + '},';
	}
	ttext += "]}";
	tq = tq + '&&' + timg + '&&' + ttext;
	return tq;
}
//txt文件保存
function strJsonToJsonByEval() {
	var tq = this.strJsonToJson();
	tq = escape(tq); //加密
	var date = new Date();
	downloadFile(date.getHours() + date.getMinutes() + date.getSeconds() + "保存码.txt", tq);
}

function downloadFile(fileName, content) {
	var aLink = document.createElement('a');
	var blob = new Blob([content]);
	var evt = document.createEvent("HTMLEvents");
	evt.initEvent("click", false, false); //initEvent 不加后两个参数在FF下会报错
	aLink.download = fileName;
	aLink.href = URL.createObjectURL(blob);
	aLink.dispatchEvent(evt);
	aLink.click();
	$("body").append($(aLink));
}